//
//  HJCNetWorkTools.swift
//  新浪微博Swift
//
//  Created by 郝俊聪 on 15/5/17.
//  Copyright (c) 2015年 heima. All rights reserved.
//

import UIKit
import SVProgressHUD
import AFNetworking

enum Method : String{
    case GET = "GET"
    case POST = "POST"
}

class HJCNetWorkTools : AFHTTPSessionManager {
    
    
    ///创建一个单例
    static let tools : HJCNetWorkTools = {
        let tools = HJCNetWorkTools()
        //拓展接收的类型
        tools.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript", "text/html","text/plain") as Set<NSObject>
        
        //设置afn请求超时时间(默认是60秒)
        tools.requestSerializer.timeoutInterval = 30
        
        //检查网路状态
        tools.reachabilityManager.setReachabilityStatusChangeBlock({ (status) -> Void in
            
            
            switch status {
            case AFNetworkReachabilityStatus.NotReachable:
                 println("你的网路断了")
            case AFNetworkReachabilityStatus.ReachableViaWWAN:
                 println("您正在使用3G")
            case AFNetworkReachabilityStatus.ReachableViaWiFi:
                 println("您正在使用WIFI")
            default:
                 println(status)
            }
            
        })
        
        
        
        return tools
    }()
    
    class func sharedNetWorkTools()->HJCNetWorkTools{
       
        
   
        return tools
    }
    
    
    
    ///普通请求
    class func requestJSON(method:Method, URLString: String, parameters: [String: AnyObject]? = nil, finished:
        (JSON:AnyObject?)->()){
            
            if method == Method.GET{
                sharedNetWorkTools().GET(URLString, parameters: parameters, success: { (_, json) -> Void in
                    
                    finished(JSON: json)
                    
                    }) { (_, error) -> Void in
                        println(error)
                        SVProgressHUD.showErrorWithStatus("你的网速不给力")
                }
            }else{
                sharedNetWorkTools().POST(URLString, parameters: parameters, success: { (_, json) -> Void in
                    
                    finished(JSON: json)
                    
                    }) { (_, error) -> Void in
                        println(error)
                        SVProgressHUD.showErrorWithStatus("你的网速不给力")
                }
                
            }
//        Alamofire.request(method, URLString, parameters: parameters).responseJSON() { (_, _, JSON, error) -> Void in
//            
//            
//            //处理错误
//            if JSON == nil || error != nil{
//                
//                //提示
//                SVProgressHUD.showErrorWithStatus("你的网速不给力哦")
//                //回调
//                finished(JSON: nil)
//                return
//            }
//            
//            //回调
//            finished(JSON: JSON)
//            
//        }
    }
    
    ///上传文字
    class func uploadText(urlstr:String,parameters: [String: AnyObject]? = nil, finished:(JSON:AnyObject?)->() ){
//        Alamofire.request(.POST, urlstr, parameters: parameters).responseJSON(options: nil) { (_,_,JSON,error) -> Void in
//            
//            if error != nil{
//               finished(JSON: nil)
//                return
//            }
//            finished(JSON: JSON)
//        }
        sharedNetWorkTools().POST(urlstr, parameters: parameters, success: { (_, JSON) -> Void in
            
            finished(JSON:JSON)
            
        }) { (_, error) -> Void in
//            println(error)
            finished(JSON:nil)
        }
    }
    
    
    ///上传图片
    static let boundary = "itheima-upload"
    class func uploadTextAndPic(urlstr:String,fieldName: String,dataList:[String: NSData!],parameters: [String: AnyObject]? = nil, finished:(error:NSError?)->() ){
        

//        //设置请求方法
//        var request = NSMutableURLRequest(URL: NSURL(string:urlstr)!)
//        request.HTTPMethod = "POST"
//        //设置content—type
//        let type = "multipart/form-data; boundary=\(boundary)"
//        request.setValue(type, forHTTPHeaderField: "Content-Type")
//        
//        let data = formData(fieldName, dataList: dataList, parameters: parameters)
//        
//        NSURLSession.sharedSession().uploadTaskWithRequest(request, fromData: data) { (responeJson, _, error) -> Void in
//            
//            if error != nil{
//               println(error)
//               finished(error: error)
//               return
//            }
//            let json = NSJSONSerialization.JSONObjectWithData(responeJson, options: NSJSONReadingOptions.allZeros, error: nil) as! NSDictionary
////            println("json---\(json)")
//            finished(error: nil)
//            
//        }.resume()
    
        sharedNetWorkTools().POST(urlstr, parameters: parameters, constructingBodyWithBlock: { (fileData) -> Void in
            
            for (k,v) in dataList{
                fileData.appendPartWithFileData(v, name: fieldName, fileName: k, mimeType: "application/octet-stream")
                
            }
        }, success: { (_, JSON) -> Void in
            
            finished(error: nil)
            
        }) { (_, error) -> Void in
            finished(error: error)
        }
        
        
    }
    ///将需要发送的post的body转成二进制
    private class func formData(fieldName:String,dataList:[String:NSData!],parameters: [String: AnyObject]? = nil)->NSData{
        
        var dataM = NSMutableData()
        
        //1.遍历字典，拼接字符串参数
        if let params = parameters{
            for(k,v) in params{
                
                var strM = "--\(boundary)\r\n"
                strM += "Content-Disposition: form-data; name=\"\(k)\"\r\n\r\n"
                strM += "\(v)\r\n"
                
                dataM.appendData(strM.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
            
            }
        }
        
        //2遍历文件数据
        for (k,v) in dataList{
            var strM = "--\(boundary)\r\n"
            strM += "Content-Disposition: form-data; name=\"\(fieldName)\"; filename=\"\(k)\"\r\n"
            strM += "Content-Type: application/octet-stream\r\n\r\n"
            
            dataM.appendData(strM.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
            
            //追加文件
            dataM.appendData(v)
            dataM.appendData("\r\n".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
        }
        
        //3.请求结尾字符串，告诉服务器，上传数据已经结束
        let tail = "--\(boundary)--\r\n"
        dataM.appendData(tail.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)!)
        
        //返回二进制数据
        return dataM
        
    }
    
    
   
}
